using System;
using System.ComponentModel;

namespace PropertyExpression.CalcExpression
{
    internal class PropertyValue<TProperty> : IValue<TProperty>
    {
        public event Action Changed;

        private readonly IPropertyHolder<TProperty> propertyHolder;

        private bool isInvalidate;

        internal PropertyValue(INotifyPropertyChanged entity, IPropertyHolder<TProperty> propertyHolder)
        {
            this.propertyHolder = propertyHolder;

            isInvalidate = true;

            entity.PropertyChanged += Entity_OnPropertyChanged;
        }

        private void Entity_OnPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == propertyHolder.PropertyName)
            {
                OnChanged();
            }
        }

        private void OnChanged()
        {
            isInvalidate = true;
            if (Changed != null) Changed();
        }

        private TProperty primVal;

        public TProperty PrimVal
        {
            get
            {
                if (isInvalidate)
                {
                    primVal = propertyHolder.GetValue();
                    isInvalidate = false;
                }
                return primVal;
            }
        }

        public override string ToString()
        {
            return PrimVal.ToString();
        }
    }
}